package com.ruan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruan.common.Code;
import com.ruan.common.Result;
import com.ruan.mapper.EmployeeMapper;
import com.ruan.mapper.OnDutyMapper;
import com.ruan.mapper.TasksMapper;
import com.ruan.pojo.*;
import com.ruan.service.EmployeeService;
import com.ruan.service.OnDutyService;
import com.ruan.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class OnDutyServiceImpl extends ServiceImpl<OnDutyMapper, OnDuty> implements OnDutyService {

    @Autowired
    private OnDutyMapper onDutyMapper;

    @Autowired
    private OnDutyService ondutyService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private TasksMapper tasksMapper;

//    /**
//     * 分页条件查询上月份的出勤数据列表
//     * @param currentPage 当前页
//     * @param pageSize 每页最大数
//     * @param ltoQueryCondition 查询条件
//     * @return
//     */
//    @Override
//    public Result selectOnDutyDTO(int currentPage,
//                                  int pageSize,
//                                  LTOQueryCondition ltoQueryCondition) {
//        System.out.println("selectOnDutyDTO的参数是"+ltoQueryCondition);
//        Date month = ltoQueryCondition.getMonth();//2024-2-1
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-01");
//        String firstDay = sdf.format(month);
////        System.out.println("第一天------"+firstDay);
//        String lastDay = DateUtils.getLastDay(firstDay);//每月最后一天
//
//        LambdaQueryWrapper<OnDuty> queryWrapper =new LambdaQueryWrapper<>();
//        //----------------------------------------------------
//        LambdaQueryWrapper<Employee> queryWrapper1 =new LambdaQueryWrapper<>();
//        queryWrapper1.like(Employee::getName,ltoQueryCondition.getName());
//        List<Employee> employeeList = employeeMapper.selectList(queryWrapper1);
//        List<Long> employeeIds = employeeList.stream().map(Employee::getId).collect(Collectors.toList());
////        wrapper.in("employee_id", employeeIds);//是QueryWrapper的技术语句
//        queryWrapper.in(OnDuty::getEmployeeId, employeeIds);
////        for (Employee employee : employeeList) {
////            // 在这里处理每个部门对象
////            queryWrapper.eq(ltoQueryCondition.getName()!=null,OnDuty::getEmployeeId,employee.getId());
////        }
//        queryWrapper.eq(ltoQueryCondition.getDepartmentId()!=null,OnDuty::getDepartmentId,ltoQueryCondition.getDepartmentId());
////        queryWrapper.like(ltoQueryCondition.getName()!=null,OnDuty::getName,ltoQueryCondition.getName());
//        queryWrapper.between(OnDuty::getDay,firstDay,lastDay);
//        queryWrapper.groupBy(OnDuty::getEmployeeId);
////        queryWrapper.groupBy(OnDuty::getPhone);
//
//        Page<OnDuty> iPage = new Page<>(currentPage,pageSize);
//        onDutyMapper.selectPage(iPage, queryWrapper);
////        System.out.println("total-->>>"+iPage.getTotal());
//        List<OnDuty> onDuties = iPage.getRecords();
////        System.out.println("onDuties->>>>>>"+onDuties);
//        List<OnDutyDTO> onDutyDTOList = new ArrayList<>();
//        for (OnDuty onDuty : onDuties) {
//            OnDutyDTO onDutyDTO = new OnDutyDTO();
//            System.out.println("onDuty是："+onDuty);
//            Long employeeId = onDuty.getEmployeeId();
//            List<String> status = onDutyMapper.selectStatus(employeeId,firstDay,lastDay);
////---------------------------------------------------
////            QueryWrapper<OnDuty> Wrapper = new QueryWrapper<>();
////            Wrapper.select("status")
////                    .eq("employeeId", onDuty.getEmployeeId())
////                    .between("day", firstDay, lastDay);
////            List<String> status = onDutyMapper.select(Wrapper);
//
////            List<String> status = onDutyMapper.selectStatus(onDuty.getPhone(),firstDay,lastDay);
//                System.out.println("status是：" + status);
//                onDutyDTO.setStatus(status);
//
//            onDutyDTO.setTotal(iPage.getTotal());
//            BeanUtils.copyProperties(onDuty,onDutyDTO);
//            onDutyDTOList.add(onDutyDTO);
//        }
////        System.out.println(onDutyDTOList);
//        return new Result(Code.SELECT_OK,iPageExt);
////        return onDutyDTOList;
//    }

    /**
     * 将打卡信息导出为Excel
     * @throws Exception
     * @return
     */
    @Override
    public byte[] exportToExcel(Integer id) {
        LambdaQueryWrapper<OnDuty> queryWrapper = new LambdaQueryWrapper();
        if (id == null) {
            // 如果 id 为 null，查询所有
            queryWrapper = null;
        } else {
            // 如果 id 有值，添加相应的查询条件
            //log.info("查询id为{}的员工负责的项目", id);
            queryWrapper.eq(OnDuty::getEmployeeId, id);
        }
        List<OnDuty> onDutyList = onDutyMapper.selectList(queryWrapper);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //工作簿，允许您在Java应用程序中创建、读取和修改Excel文件
        XSSFWorkbook excel=new XSSFWorkbook();
        //创建一个工作表对象
        XSSFSheet sheet = excel.createSheet("sheet1");


        String[] headers = {"员工姓名","工号","日期",
                "上班时间","下班时间","工时"};

        XSSFRow row1 = sheet.createRow(0);

        for (int i = 0; i < headers.length; i++) {
            row1.createCell(i).setCellValue(headers[i]);
        }

        for (int i = 0; i < onDutyList.size(); i++) {
            OnDuty onDuty = onDutyList.get(i);
            String day = String.valueOf(onDuty.getDay());
//            if(onDuty.getDay() != null){
//                // 解析字符串为 LocalDateTime
//                LocalDateTime dateTime = LocalDateTime.parse(day);
//                // 格式化为只包含日期部分的字符串
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//                day = dateTime.format(formatter);
//            }


            XSSFRow row2 = sheet.createRow(i+1);
            Employee employee = new Employee();
            if(onDuty != null){
                if(onDuty.getEmployeeId() != null) {
                    employee = employeeService.getById(onDuty.getEmployeeId());//报空指针。。。。。。
                }

                String[] onDutyInfo = {
                        employee.getName(),employee.getJobId(),
                        onDuty.getDay() != null ? day : "",
                        onDuty.getArriveTime() != null ? String.valueOf(onDuty.getArriveTime()) : "",
                        onDuty.getLeaveTime() != null ? String.valueOf(onDuty.getLeaveTime()) : "",
                        //工时计算
                        onDuty.getLeaveTime() != null && onDuty.getArriveTime() != null ?
                                calculateWorkHours(String.valueOf(onDuty.getArriveTime()), String.valueOf(onDuty.getLeaveTime())) : ""
                };

                for (int j = 0; j < onDutyInfo.length; j++) {
                    row2.createCell(j).setCellValue(onDutyInfo[j]);
                }
            }
        }

        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        header.setContentDispositionFormData("attachment","工时表.xlsx");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            excel.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputStream.toByteArray();
    }

    /**
     * 工时计算
     * @param arriveTimeStr
     * @param leaveTimeStr
     * @return
     */
    public static String calculateWorkHours(String arriveTimeStr, String leaveTimeStr) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        LocalTime arriveTime = LocalTime.parse(arriveTimeStr, formatter);
        LocalTime leaveTime = LocalTime.parse(leaveTimeStr, formatter);

        Duration duration = Duration.between(arriveTime, leaveTime);
        long seconds = duration.getSeconds();

        long hours = seconds / 3600;
        long minutes = (seconds % 3600) / 60;
        long remainingSeconds = seconds % 60;

        return String.format("%02d:%02d:%02d", hours, minutes, remainingSeconds);
    }

    /**
     * 获取出差记录的status，判断是否打卡
     * @param phone 员工手机号
     * @return
     */
    @Override
    public Result getOnDutyStatus(String phone) {

        LambdaQueryWrapper<OnDuty> queryWrapper = new LambdaQueryWrapper<>();
        //-----------------------------------
        LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Employee::getPhone,phone);
        Employee employee = employeeMapper.selectOne(queryWrapper1);
        if(employee!=null){
            queryWrapper.eq(OnDuty::getEmployeeId,employee.getId());
        }
        Date date = new Date(System.currentTimeMillis());
        queryWrapper.eq(OnDuty::getDay,date);

        int count = onDutyMapper.selectCount(queryWrapper);
        if (count == 0){
            return new Result(Code.ONDUTY_ERR,"今天还未打卡,请及时打卡！");
        }else if(count == 1) {
            OnDuty onDuty = onDutyMapper.selectOne(queryWrapper);
            LambdaQueryWrapper<OnDuty> queryWrapperQuery = new LambdaQueryWrapper<>();
            Date day = new Date(System.currentTimeMillis());
            if(employee!=null) {
                queryWrapperQuery.eq(OnDuty::getEmployeeId, employee.getId());
            }
            queryWrapperQuery.eq(OnDuty::getDay,day);
//            OnDuty onDuty1 = onDutyMapper.selectOne(queryWrapperQuery);
//            System.out.println("onDuty1是"+onDuty1);

            //如果不等于null，肯定完成了上班打卡
            Time leaveTime = onDuty.getLeaveTime();
            if (leaveTime!=null){
                return new Result(Code.ONDUTY_START_END_OK,"今天已完成全部打卡！");
            }else {
                return new Result(Code.ONDUTY_END_ERR,"今天已完成上班打卡，未下班打卡！");
            }
        }else {
            return new Result(Code.ONDUTY_ERR,"今天重复打卡");
        }
    }


    /**
     * 员工打卡上班，新增出勤记录
     * @param punchInRequestBody(location,onDuty) 出勤记录
     * @return
     */
    @Override
    @Transactional
    public Result punchIn(PunchInRequestBody punchInRequestBody) {
//        System.out.println("punchIn传的什么参数："+punchInRequestBody);
        //使用 System.currentTimeMillis() 方法获取当前系统时间的毫秒数，
        // 并将其传递给 Date 构造函数，从而创建了一个代表当前时间的 Date 对象。
        Date day = new Date(System.currentTimeMillis());
        //查一查该员工今天是否已经打卡
        if(punchInRequestBody.getEmployeeIds() == null ||
                punchInRequestBody.getEmployeeIds().size() == 0){
            return new Result(Code.ONDUTY_ERR,"请选择打卡的员工！");
        }

        Time nowTime = null;
        int punchIned = 0;
        for(String employeeId : punchInRequestBody.getEmployeeIds()){
            LambdaQueryWrapper<OnDuty> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OnDuty::getEmployeeId, employeeId);
            queryWrapper.eq(OnDuty::getDay, day);
            int count = onDutyMapper.selectCount(queryWrapper);
//            System.out.println("count是"+count);
            if (count == 1) {
                OnDuty onDuty1 = onDutyMapper.selectOne(queryWrapper);
                nowTime = onDuty1.getArriveTime();
                punchIned = punchIned + 1;
                continue;
//                System.out.println(punchIned+"人已打卡");
//                return new Result(Code.ONDUTY_START_OK, ArriveTime, "只记录第一次打卡时间！");
            } else if (count > 1) {
//                System.out.println("删除多余的打卡记录，只留下一条");
                //删除多余的打卡记录，只留下一条
                List<OnDuty> list = onDutyMapper.selectList(queryWrapper);
                // 保留 list 中的第一条记录，其他的删除
                // 确保保留的记录是否正确
                OnDuty recordToKeep = list.get(0);
                // 删除多余的记录
                for (OnDuty onDuty : list) {
                    if (!onDuty.equals(recordToKeep)) {
                        onDutyMapper.deleteById(onDuty.getId());
                    }
                }
                continue;
            }else{
                nowTime = new Time(System.currentTimeMillis());
                OnDuty onDuty = new OnDuty();
                onDuty.setEmployeeId(Long.valueOf(employeeId));
                //设置员工的到岗时间为当前时间 nowTime
                onDuty.setArriveTime(nowTime);
                //设置员工的工作日期
                onDuty.setDay(day);
                onDutyMapper.insert(onDuty);
            }
        }
//        System.out.println("nowTime是"+nowTime);
        String ArriveTime = String.valueOf(nowTime);
        if(punchIned > 0){
//            System.out.println("punchIned是"+punchIned);
            return new Result(Code.ONDUTY_START_OK, ArriveTime,"有"+punchIned+"人已经上班打卡");
        }
        return new Result(Code.ONDUTY_START_OK, ArriveTime,"上班打卡成功！");
    }


    //员工打卡下班
    //员工手机号
    @Override
    @Transactional
    public Result punchOut(String phone) {
        //System.out.println("punchOut传的是："+phone);
        Date day = new Date(System.currentTimeMillis());
        //找到打卡人
        LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Employee::getPhone,phone);
        int count = employeeMapper.selectCount(queryWrapper1);
        if(count > 1){
            return new Result(Code.ONDUTY_ERR,"该手机号已注册多个员工，请联系管理员");
        }else if(count == 0){
            return new Result(Code.ONDUTY_ERR,"找不到员工信息");
        }
        Employee employee = employeeMapper.selectOne(queryWrapper1);

        LambdaQueryWrapper<OnDuty> queryWrapper = new LambdaQueryWrapper<>();
//        if(employee!=null){
            queryWrapper.eq(OnDuty::getEmployeeId,employee.getId());
//        }
        queryWrapper.eq(OnDuty::getDay,day);
        Integer count1 = onDutyMapper.selectCount(queryWrapper);
        if(count1 == 0){
            return new Result(Code.ONDUTY_ERR,"请先打卡上班！");
        }else if(count1 > 1){
            return new Result(Code.ONDUTY_ERR,"重复打卡，请联系管理员");
        }
        //断网状态下上班打卡，可能会生成多条出勤记录？？？
        OnDuty onDuty = onDutyMapper.selectOne(queryWrapper);
        Time nowTime = new Time(System.currentTimeMillis());

        //能否查到该用户的onDuty()当天打卡上班的记录
//        String LeaveTime = String.valueOf(onDuty.getLeaveTime());
//        System.out.println("LeaveTime是"+onDuty.getLeaveTime());

        if (onDuty == null || onDuty.getArriveTime() == null) {
            return new Result(Code.ONDUTY_END_ERR, "请先上班打卡！");
        } else if(onDuty.getLeaveTime() != null){
            return new Result(Code.ONDUTY_END_ERR,onDuty.getLeaveTime(),"你已下班，请勿重复打卡！");
        }else if(onDuty.getLeaveTime() == null){
//            System.out.println("onDuty是"+onDuty);
            onDuty.setLeaveTime(nowTime);
            onDutyMapper.updateById(onDuty);
            //当天的所有任务以及员工在前端的头像变灰色
            LambdaQueryWrapper<Tasks> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(Tasks::getEmployeeId,employee.getId());
            queryWrapper2.eq(Tasks::getDate,day);
            List<Tasks> tasks = tasksMapper.selectList(queryWrapper2);
            //所有任务都完成
            if(tasks.size() != 0) {
                for (Tasks task : tasks) {
                    task.setCompletionStatus(Tasks.CompletionStatus.completed);
                    tasksMapper.updateById(task);
                }
            }
            return new Result(Code.ONDUTY_END_OK,onDuty.getLeaveTime(),"下班打卡成功！");
        }else {
            return new Result(Code.ONDUTY_END_ERR,onDuty.getLeaveTime(),"请勿重复打卡！");
        }
    }

    @Override
    @Transactional
    public Result batchPunchOut(PunchInRequestBody punchInRequestBody) {
//        System.out.println("batchPunchOut传的是："+punchInRequestBody);

        if(punchInRequestBody.getEmployeeIds() == null ||
                punchInRequestBody.getEmployeeIds().size() == 0){
            return new Result(Code.ONDUTY_ERR,"请选择需要打卡下班的员工！");
        }

        OnDuty onDuty = null;
        List<String> employeeIds = punchInRequestBody.getEmployeeIds();
        Date day = new Date(System.currentTimeMillis());
        if(punchInRequestBody.getEmployeeIds().size() == 1){
            LambdaQueryWrapper<OnDuty> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OnDuty::getEmployeeId,employeeIds.get(0));
            queryWrapper.eq(OnDuty::getDay,day);
            Integer count = onDutyMapper.selectCount(queryWrapper);

            if(count == 0){
                return new Result(Code.ONDUTY_ERR,"请先上班打卡！");
            }else if(count > 1){
                return new Result(Code.ONDUTY_ERR,"重复打卡，请联系管理员");
//                //删除多余的打卡记录，只留下一条
//                List<OnDuty> list = onDutyMapper.selectList(queryWrapper);
//                // 保留 list 中的第一条记录，其他的删除
//                // 确保保留的记录是否正确
//                OnDuty recordToKeep = list.get(0);
//                // 删除多余的记录
//                for (OnDuty onDuty : list) {
//                    if (!onDuty.equals(recordToKeep)) {
//                        onDutyMapper.deleteById(onDuty.getId());
//                    }
//                }
            }else {
                onDuty = onDutyMapper.selectOne(queryWrapper);
                Time nowTime = new Time(System.currentTimeMillis());
                if(onDuty.getLeaveTime() != null){
                    return new Result(Code.ONDUTY_ERR,onDuty.getLeaveTime(),"你已下班，请勿重复打卡！");
                }
                onDuty.setLeaveTime(nowTime);
                onDutyMapper.updateById(onDuty);
                //当天的所有任务以及员工在前端的头像变灰色
                LambdaQueryWrapper<Tasks> taskQueryWrapper = new LambdaQueryWrapper<>();
                taskQueryWrapper.eq(Tasks::getEmployeeId,onDuty.getEmployeeId());
                taskQueryWrapper.eq(Tasks::getDate,day);
                List<Tasks> tasks = tasksMapper.selectList(taskQueryWrapper);
                //所有任务都完成
                if(tasks.size() != 0){
                    for (Tasks task : tasks) {
                        task.setCompletionStatus(Tasks.CompletionStatus.completed);
                        tasksMapper.updateById(task);
                    }
                }
                return new Result(Code.ONDUTY_OK,onDuty.getLeaveTime(),"单独下班打卡成功");
            }
        }
        //1.方法一
//        List<Employee> unPunchIned = null;
//        List<Employee> punchOuted = null;
//        List<OnDuty> ondutyList = employeeIds.stream()
//                .filter(employeeId ->
//                        /* 条件判断，如果满足条件则保留，否则过滤掉 */ )
//                .map(employeeId -> {
//
//                    LambdaQueryWrapper<OnDuty> queryWrapper = new LambdaQueryWrapper<>();
//                    queryWrapper.eq(OnDuty::getEmployeeId, employeeId);
//                    queryWrapper.eq(OnDuty::getDay, day);
//                    queryWrapper.isNull(OnDuty::getArriveTime);
//                    queryWrapper.isNull(OnDuty::getLeaveTime);
//                    if (onDutyMapper.selectCount(queryWrapper) > 0) {
//                        unPunchIned.add(employeeMapper.selectById(employeeId));
////                        return new Result(Code.ONDUTY_ERR,"请先上班打卡！");
//                    }
//                    LambdaQueryWrapper<OnDuty> queryWrapper1 = new LambdaQueryWrapper<>();
//                    queryWrapper1.eq(OnDuty::getEmployeeId, employeeId);
//                    queryWrapper1.eq(OnDuty::getDay, day);
//                    queryWrapper1.isNotNull(OnDuty::getArriveTime);
//                    queryWrapper1.isNotNull(OnDuty::getLeaveTime);
//                    if (onDutyMapper.selectCount(queryWrapper1) > 0) {
//                        punchOuted.add(employeeMapper.selectById(employeeId));
////                        return new Result(Code.ONDUTY_ERR,"请先上班打卡！");
//                    }
//                    LambdaQueryWrapper<OnDuty> queryWrapper2 = new LambdaQueryWrapper<>();
//                    queryWrapper2.eq(OnDuty::getEmployeeId, employeeId);
//                    queryWrapper2.eq(OnDuty::getDay, day);
//                    List<OnDuty> ondutyList1 = onDutyMapper.selectList(queryWrapper2);
//                    if (ondutyList1.size() > 1) {
//                        //删除多余的记录？？
//                        //删除多余的打卡记录，只留下一条
////                        List<OnDuty> list = onDutyMapper.selectList(queryWrapper2);
//                        // 保留 list 中的第一条记录，其他的删除
//                        // 确保保留的记录是否正确
//                        OnDuty recordToKeep = ondutyList1.get(0);
//                        // 删除多余的记录
//                        for (OnDuty onDuty : ondutyList1) {
//                            if (!onDuty.equals(recordToKeep)) {
//                                onDutyMapper.deleteById(onDuty.getId());
//                            }
//                        }
//                    }else if(ondutyList1.size() == 0){
//                        punchOuted.add(employeeMapper.selectById(employeeId));
//                    }
//                    queryWrapper2.isNotNull(OnDuty::getArriveTime);
//                    queryWrapper2.isNull(OnDuty::getLeaveTime);
//                    OnDuty onduty = onDutyMapper.selectOne(queryWrapper2);
//
//                    // 设置其他属性，例如：
//                    onduty.setLeaveTime(new Time(System.currentTimeMillis()));
//                    return onduty;
//                })
//                .collect(Collectors.toList());
//
//        ondutyService.updateBatchById(ondutyList);

        //1.方法二
//        List<Employee> unPunchIned = null;
//        List<Employee> punchOuted = null;
        int unPunchIned = 0;
//        int unPunchInAndOut = 0;
        int punchInAndOut = 0;
        for (String employeeId : employeeIds) {
            LambdaQueryWrapper<OnDuty> onDutyQueryWrapper = new LambdaQueryWrapper<>();
            onDutyQueryWrapper.eq(OnDuty::getEmployeeId, employeeId);
            onDutyQueryWrapper.eq(OnDuty::getDay, day);
            onDutyQueryWrapper.isNotNull(OnDuty::getArriveTime);
            onDutyQueryWrapper.isNotNull(OnDuty::getLeaveTime);

            if (onDutyMapper.selectCount(onDutyQueryWrapper) > 0) {
                punchInAndOut = punchInAndOut + 1;
                continue;//上下班都已打卡，跳过本次循环，继续下一次循环
            }
            LambdaQueryWrapper<OnDuty> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OnDuty::getEmployeeId, employeeId);
            queryWrapper.eq(OnDuty::getDay, day);
            //有人未上班打卡
//            queryWrapper.isNull(OnDuty::getArriveTime);
//            queryWrapper.isNull(OnDuty::getLeaveTime);
            if (onDutyMapper.selectCount(queryWrapper) == 0) {
                unPunchIned = unPunchIned + 1;
//                unPunchIned.add(employeeMapper.selectById(employeeId));
                continue;//上班未打卡，跳过本次循环，继续下一次循环
//                return new Result(Code.ONDUTY_ERR,"请先上班打卡！");
            }
//            LambdaQueryWrapper<OnDuty> queryWrapper1 = new LambdaQueryWrapper<>();
//            queryWrapper1.eq(OnDuty::getEmployeeId, employeeId);
//            queryWrapper1.eq(OnDuty::getDay, day);
//            //有人已下班打卡了
//            queryWrapper1.isNull(OnDuty::getArriveTime);
//            queryWrapper1.isNull(OnDuty::getLeaveTime);
//            if (onDutyMapper.selectCount(queryWrapper1) > 0) {
//                unPunchInAndOut = unPunchInAndOut + 1;
////                punchOuted.add(employeeMapper.selectById(employeeId));
//                continue;//上下班都未打卡，跳过本次循环，继续下一次循环
////                return new Result(Code.ONDUTY_ERR,"请先上班打卡！");
//            }
            //正常可打卡人员
            LambdaQueryWrapper<OnDuty> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(OnDuty::getEmployeeId, employeeId);
            queryWrapper2.eq(OnDuty::getDay, day);
            queryWrapper2.isNotNull(OnDuty::getArriveTime);
            queryWrapper2.isNull(OnDuty::getLeaveTime);
            Integer count = onDutyMapper.selectCount(queryWrapper2);
            if (count > 1) {
                continue;
//                //删除多余的记录？？
//                //删除多余的打卡记录，只留下一条
//                List<OnDuty> list = onDutyMapper.selectList(queryWrapper2);
//                // 保留 list 中的第一条记录，其他的删除
//                // 确保保留的记录是否正确
//                OnDuty recordToKeep = list.get(0);
//                // 删除多余的记录
//                for (OnDuty onDuty : list) {
//                    if (!onDuty.equals(recordToKeep)) {
//                        onDutyMapper.deleteById(onDuty.getId());
//                    }
//                }
            }else if(count == 0){
                //无记录，说明未上班打卡
//                unPunchIned = unPunchIned + 1;
//                unPunchIned.add(employeeMapper.selectById(employeeId));
                continue;//上班未打卡，跳过本次循环，继续下一次循环
            }
            onDuty = onDutyMapper.selectOne(queryWrapper2);
            if(onDuty.getLeaveTime() != null) {
                continue;//已经下班，跳过本次循环，继续下一次循环
            }
            onDuty.setLeaveTime(new Time(System.currentTimeMillis()));
            onDutyMapper.updateById(onDuty);
            //当天的所有任务以及员工在前端的头像变灰色
            LambdaQueryWrapper<Tasks> taskQueryWrapper = new LambdaQueryWrapper<>();
            taskQueryWrapper.eq(Tasks::getEmployeeId,employeeId);
            taskQueryWrapper.eq(Tasks::getDate,day);
            List<Tasks> tasks = tasksMapper.selectList(taskQueryWrapper);
            //所有任务都完成
            if(tasks.size() != 0){
                for (Tasks task : tasks) {
                    task.setCompletionStatus(Tasks.CompletionStatus.completed);
                    tasksMapper.updateById(task);
                }
            }
        }
//        if (unPunchIned != null && unPunchIned.size() > 0 ||
//                punchOuted != null && punchOuted.size() > 0) {
//            List<String> unPunchInedName = unPunchIned.stream().map(Employee::getName).collect(Collectors.toList());
//            List<String> punchOutedName = punchOuted.stream().map(Employee::getName).collect(Collectors.toList());
//            return new Result(Code.ONDUTY_ERR, "下班打卡成功！以下员工未上班打卡：" + unPunchInedName +
//                    "，以下员工已下班打卡：" + punchOutedName);
//        }
//        System.out.println("unPunchIned是："+unPunchIned);
//        System.out.println("unPunchInAndOut是："+unPunchInAndOut);
//        System.out.println("punchInAndOut是："+punchInAndOut);

//        System.out.println("unPunchIned是"+unPunchIned);
//        System.out.println("punchInAndOut是"+punchInAndOut);
//        System.out.println("punchInRequestBody.getEmployeeIds().size()是"+punchInRequestBody.getEmployeeIds().size());
        if (unPunchIned != 0 || punchInAndOut != 0) {//unPunchInAndOut != 0 ||
            if(unPunchIned == punchInRequestBody.getEmployeeIds().size()){//全部未上班打卡
                return new Result(Code.ONDUTY_ERR,onDuty.getLeaveTime(), "全部未上班打卡");
            }
            if(punchInAndOut == punchInRequestBody.getEmployeeIds().size()){ //全部已下班打卡
                return new Result(Code.ONDUTY_ERR,onDuty.getLeaveTime(), "全部打卡下班了");
            }
            return new Result(Code.ONDUTY_ERR,onDuty.getLeaveTime(), "批量下班打卡部分失败！共有" + unPunchIned +
                    "人未打卡上班，" + punchInAndOut + "人已经打卡下班");
        }

        return new Result(Code.ONDUTY_OK,onDuty.getLeaveTime(), "批量下班打卡成功！");
    }

    //分页+条件 获取个人出勤记录
    //currentPage 当前页pageSize 每页最大数
    @Override
    public IPage<OnDuty> getSelfOnDuty(int currentPage,
                                       int pageSize,
                                       QuerySelfAttendanceCondition querySelfAttendanceCondition) {
        Date month = querySelfAttendanceCondition.getMonth();//2024-2-1
        IPage<OnDuty> iPage=new Page<>(currentPage,pageSize);
        LambdaQueryWrapper<OnDuty> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(querySelfAttendanceCondition.getStatus()!=null,
                OnDuty::getStatus, querySelfAttendanceCondition.getStatus());

        LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Employee::getPhone,querySelfAttendanceCondition.getPhone());
        Employee employee = employeeMapper.selectOne(queryWrapper1);
        queryWrapper.eq(OnDuty::getEmployeeId, employee.getId());

        if (month!=null){
            String firstDay = month.toString();//每月的第一天
            String lastDay = DateUtils.getLastDay(firstDay);//每月最后一天

            queryWrapper.between(OnDuty::getDay,firstDay,lastDay);
            queryWrapper.orderByDesc(OnDuty::getDay);//生效了？？
            return onDutyMapper.selectPage(iPage,queryWrapper);
        }else {
            queryWrapper.orderByDesc(OnDuty::getDay);//不生效？？
            return onDutyMapper.selectPage(iPage,queryWrapper);
        }

    }

    @Override
    public Result setOnDutyStatus(String phone, String day, String status) {

        LambdaQueryWrapper<OnDuty> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OnDuty::getDay,day);
        //--------------------------------
        LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Employee::getPhone,phone);
        int count = employeeMapper.selectCount(queryWrapper1);
        if(count > 1){
            return new Result(Code.ONDUTY_ERR,"该手机号已注册多个员工，请联系管理员");
        }else if(count == 0){
            return new Result(Code.ONDUTY_ERR,"找不到员工信息");
        }
        Employee employee = employeeMapper.selectOne(queryWrapper1);

        queryWrapper.eq(OnDuty::getEmployeeId,employee.getId());
//        queryWrapper.eq(OnDuty::getPhone,phone);
        try {
            OnDuty onDuty = onDutyMapper.selectOne(queryWrapper);
            onDuty.setStatus(status);
            onDutyMapper.updateById(onDuty);
            return new Result(Code.UPDATE_OK,"更新出勤状态成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.UPDATE_ERR,"更新出勤状态失败！");
        }


    }


}
